/*
 * Copyright (c) 2025 Huawei Device, Inc. Ltd. and <马弓手>.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "translateWgs.h"
#include <cmath>

double translateWgs::x_PI = 3.14159265358979323846 * 3000.0 / 180.0;
double translateWgs::PI = 3.1415926535897932384626;
double translateWgs::a = 6378245.0;  
double translateWgs::ee = 0.00669342162296594323;

bool translateWgs::outOfChina(double lon, double lat)
{
    return(lon<72.004 || lon>137.8374 || lat<0.8293 || lat >55.8271 || false);
}

double translateWgs::translateLon(double lon, double lat) {
   double ret = 300.0 + lon +2.0*lat + 0.1*lon*lon +0.1*lon*lat + 0.1*sqrt(abs(lon));
    ret += (20.0 * sin(6.0*lon*PI) + 20.0*sin(2.0*lon*PI)) *2.0 / 3.0;
    ret += (20.0 * sin(lon*PI) + 40.0*sin(lon/3.0 *PI)) *2.0 /3.0;
    ret += (150 * sin(lon/12.0 *PI) + 300.0*sin(lon/30.0 * PI)) *2.0 /3.0;
    return ret;
}

double translateWgs::translateLat(double lon, double lat) 
{
   double ret = -100 + 2.0*lon + 3.0*lat + 0.2*lat*lat + 0.1*lon*lat + 0.2*sqrt((abs(lon)));
    ret += (20.0 *sin(6.0*lon*PI) + 20*sin(2.0*lon*PI)) *2.0 /3.0;
    ret += (20.0 *sin(lat*PI) + 40.0*sin(lat/3.0*PI)) *2.0 /3.0;
    ret += (160.0*sin(lat/12.0*PI) + 320.0*sin(lat/30.0 *PI)) *2.0 /3.0;
    return ret;
}

void translateWgs::wgs84ToGcj02(double wgsLat, double wgsLon, double& gcjLat, double& gcjLon) 
{
    if(outOfChina(wgsLon,wgsLat))
    {
        gcjLon = wgsLon;
        gcjLat = wgsLat;
    }
    else
    {
        double dlat = translateLat(wgsLon - 105.0,wgsLat - 35.0);
        double dlon = translateLon(wgsLon - 105.0,wgsLat - 35.0);
        double radlat = wgsLat/180.0 * PI;
        double magic = sin(radlat);
        magic = 1 - ee*magic*magic;
        double squrtmagic = sqrt(magic);
        dlon = (dlon *180.0)/(a/squrtmagic*cos(radlat)*PI);
        dlat = (dlat *180.0)/((a*(1-ee))/(magic * squrtmagic)*PI);
        gcjLon = wgsLon + dlon;
        gcjLat= wgsLat +dlat;
    }
}

void translateWgs::gcj02toBd09(double gcjLon, double gcjLat, double& bd09Lon, double& bd09Lat)
{
     double z = sqrt(gcjLon*gcjLon + gcjLat*gcjLat) + 0.00002*sin(gcjLat * x_PI);
     double theta = atan2(gcjLat,gcjLon) + 0.000003 * cos(gcjLon * x_PI);
     bd09Lon = z*cos(theta) + 0.0065;
     bd09Lat = z*sin(theta) + 0.006;
}